package cate.game.farm.local;

import cate.game.GameBody;
import cate.game.db.SaveConstants;
import cate.game.farm.local.adventure.AdventureManager;
import cate.game.farm.local.endless.EndlessManager;
import cate.game.farm.local.forbidden.ForbiddenManager;
import cate.game.farm.local.island.IslandManager;
import cate.game.farm.local.udgpalace.UdgPalaceManager;
import cate.game.framework.ModuleMan;
import cate.game.util.IntervalCounter;
import cp.solution.ops.status.ModOprStatus;

import java.util.concurrent.atomic.AtomicInteger;


/** 本服玩法管理 */
public class FarmLocalManager extends ModuleMan {
    public AdventureManager adventure = new AdventureManager();

    public IslandManager island = new IslandManager();

    public ForbiddenManager forbidden = new ForbiddenManager();

    public EndlessManager endless = new EndlessManager();
    public UdgPalaceManager udgPalace = new UdgPalaceManager();

    @Override
    public void initIndependent(GameBody game) throws Exception {
        super.initIndependent(game);
        adventure.initIndependent(game);
        island.initIndependent(game);
        forbidden.initIndependent(game);
        endless.initIndependent(game);
        udgPalace.initIndependent(game);
    }

    @Override
    public void initDependent() throws Exception {
        adventure.initDependent();
        island.initDependent();
        forbidden.initDependent();
        endless.initDependent();
        udgPalace.initDependent();
    }

    @Override
    public void shutdown(){
        adventure.shutdownSafe();
        island.shutdownSafe();
        forbidden.shutdownSafe();
        udgPalace.shutdown();
    }

    @Override
    public void onDaySpan(){
        island.onDaySpanSafe();
        forbidden.onDaySpan();
        endless.onDaySpanSafe();
        udgPalace.onDaySpanSafe();
    }

    @Override
    public void onWeekSpan() {
        super.onWeekSpan();
        forbidden.onWeekSpan();
    }

    private static final AtomicInteger IDX = new AtomicInteger(0);
    private final IntervalCounter saveTrigger = new IntervalCounter(SaveConstants.FARM_SAVE_SECONDS, IDX.getAndIncrement());

    public void tick(){
        if(saveTrigger.trigger()){
            long start = System.currentTimeMillis();
            shutdown();
            log.debug("game farm定时保存完成, cost{} ms", System.currentTimeMillis() - start);
        }
    }

    @Override
    public ModOprStatus handleMergeSettle() {
        ModOprStatus item = new ModOprStatus("farm");
        return item.exe(() -> {
            log.info("无尽试炼开始合服结算排行榜");
            endless.onDaySpan();
        });
    }
}